package com.vil.config;


import com.vil.common.Constants;
import com.vil.common.ResponseUtil;
import com.vil.common.ServerResponse;
import com.vil.entity.Admin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserDetailsService userDetailsService;

    HttpSession session;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().antMatchers("/login/login.html").permitAll();

        http.headers().frameOptions().disable();
        http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
        //配置未验证状态请求数据所返回的内容
//        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint());
        http.logout().logoutSuccessUrl("/login/login.html");
//        http.logout().logoutUrl("/login/login.html");
        //记住我
        http.rememberMe().rememberMeParameter("remember");
    }

    /** 放行静态资源 */
    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/css/**","/js/**","/images/**","/lib/**","/myjs/**","/ueditor/**","/upload/**");
//        web.ignoring().antMatchers("/res/**");
    }
    /**
     * 配置密码的加密类
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationSuccessHandler successHandler(){
        return (httpServletRequest, httpServletResponse, authentication) -> {
            //获取session
            HttpSession session = httpServletRequest.getSession();
            //获取circleUser
            Admin circleUser = (Admin) session.getAttribute(Constants.USER_SESSION);
             ServerResponse.buildSuccessMsg("登陆成功").buildSuccessData(circleUser);
        };
    }

    public AuthenticationEntryPoint authenticationEntryPoint(){
        return (httpServletRequest, httpServletResponse, e) -> {
            ResponseUtil.responseJson(httpServletResponse,ServerResponse.buildErrorMsg("您还未登录！"));
        };
    }

    public AuthenticationFailureHandler failureHandler(){
        return (httpServletRequest, httpServletResponse, e) -> {
            ResponseUtil.responseJson(httpServletResponse,ServerResponse.buildErrorMsg("账号或密码错误"));
        };
    }

//    public LogoutHandler logoutHandler(){
//        Admin circleUser = (Admin)  session.getAttribute(Constants.USER_SESSION);
//        circleUser=null;
//        return null;
//    }

    public AccessDeniedHandler accessDeniedHandler(){
        return (httpServletRequest, httpServletResponse, e) -> {
            ResponseUtil.responseJson(httpServletResponse,ServerResponse.buildErrorMsg("您的权限不足"));
        };
    }



}
